package com.xxx.control.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.dylanc.viewbinding.inflateBindingWithGeneric

abstract class BaseVMFragment<V : ViewBinding, VM : BaseViewModel> :
    BaseLazyFragment() {

    private var _binding: V? = null
    val binding: V get() = _binding!!

    // ViewModel
    protected lateinit var mViewModel: VM
    override fun initLazyLoad() {
        if (!isLazyLoad) {
            initViewModel()

        }
        super.initLazyLoad()
    }


    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val viewModelClass: Class<VM>? = ClassUtil.getViewModel(this)
        if (viewModelClass != null) {
            mViewModel = ViewModelProvider(this)[viewModelClass]
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = inflateBindingWithGeneric(layoutInflater, container, false)
        return binding.root
    }


    /**
     * 失败后点击刷新
     */
    protected open fun onRefresh() {

    }


    /**
     * 初始化ViewModel
     */
    protected fun <VM : BaseViewModel?> genericViewModel(cls: Class<VM>?): VM {
        val model = ViewModelProvider(this)[cls!!]
        return model
    }

}